package com.szwistar.common.comm;

import java.nio.ByteOrder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


class ZktEncoder implements ProtocolEncoder {
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		ZktCmd frame = (ZktCmd)message;
		out.write(frame.encode());
	}

	@Override
	public void dispose(IoSession session) throws Exception {
	}
}

class ZktDecoder extends PrefixedFrameDecoder {
	public ZktDecoder() {
		super(ZktFrame.PREFIX, 4, 12, 1024);
	}

	@Override
	int peekLength(IoBuffer buf) {
		buf.order(ByteOrder.LITTLE_ENDIAN);
		return super.peekLength(buf);
	}

	@Override
	public boolean decodeFrame(IoSession session, IoBuffer in, boolean isFrameLengthSure, ProtocolDecoderOutput out) throws Exception {
		ZktAck frame = ZktAck.decode(in);
		if(frame != null) {
			out.write(frame);
			return true;
		}
		return false;	
	}
}

/**
 * ZKT中控科技 流数据帧编解码器
 */
public class ZktCodec {
	public static ProtocolCodecFilter newFilter() {
		ZktDecoder decoder = new ZktDecoder();
		ZktEncoder encoder = new ZktEncoder();
		ProtocolCodecFilter filter = new ProtocolCodecFilter(encoder, decoder);
		return filter;
	}
}
